home *** CD-ROM | disk | FTP | other *** search
- From: Philippe Verdy <100105.3120@compuserve.com>
- Message-ID: <4jc2fa$bqu@arl-news-svc-2.compuserve.com>
- X-Original-Date: 27 Mar 1996 18:47:05 GMT
- Path: in1.uu.net!bounce-back
- Date: 27 Mar 96 21:41:18 GMT
- Approved: fjh@cs.mu.oz.au
- Newsgroups: comp.std.c++
- Subject: Re: double const declarations
- Organization: CompuServe Incorporated
- X-Auth: PGPMoose V1.1 PGP comp.std.c++
- iQBFAgUBMVm2I+EDnX0m9pzZAQGy5gF/S0GJD+hXSzmJB2uFn7v6OdnfDHfDryGo
- 1u/ygQAqFUVtf43Iyh5GB/yJl6uxw2Ye
- =9Hub
-
- dak <pierreba@poster.cae.ca> s'icrit :
- > I've just encountered a problem in one of our template design and wondered
- > what could be done about it. It concerns const reference return value from
- > a templated member function, for example:
- >
- > template <class T> class SmartPtr
- > {
- > // ... whatever:
- > public:
- > const T & Dereference ();
- > };
- >
- > The problem arise when T is instantiated with a Container of constants:
- >
- > SmartPtr<const int> a;
- >
- > Here we have a double const which is not supported by the compiler, nor the
- > standard, I believe. Is there a fix or should we abandon all hope of using
- > const returns in templates ?
-
- Declare a temporary template<class T> to use <T> types only, but no <const T>,
- then create another template class that will use <const T> as the parameter
- of the first template.
- To make this class usable for const and non-const references, you can add
- another template parameter to the first class : one for the case T should be
- const, one for the other case.
- Example:
-
- template <class T, class CT>
- class SmartPtr2 {
- SmartPtr2(T* p) { mp = const_cast<CT>(p) ; }
- CT & Dereference() {
- return *mp ;
- }
- private :
- CT *mp ;
- } ;
- template <class T> class ConstSmartPtr : SmartPtr<T, T> {} ;
- template <class T> class FreeSmartPtr : SmartPtr<T, const T> {} ;
-
- Now you can safely use:
- FreeSmartPtr<const X> and ConstSmartPtr<X>.
-
- You cannot use:
- ConstSmartPtr<const X>
- due to the double const problem;
-
- But you can use:
- FreeSmartPtr<X>
- no const at all !
- ---
- [ comp.std.c++ is moderated. To submit articles: try just posting with ]
- [ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
- [ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
- [ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
- [ Comments? mailto:std-c++-request@ncar.ucar.edu ]
-